package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hy.corecode.idgen.WFGIdGenerator;
import io.xxx.xbutler.data.RobotRoomMapper;
import io.xxx.xbutler.data.RoomMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.RobotRoom;
import io.xxx.xbutler.domain.Room;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 获取群信息接口（异步）回调
 *
 * <pre>
 * {
 *     "Data": {
 *         "is_top": false,
 *         "chatroom_id": "56514793648@chatroom",
 *         "chatroom_name": "小助手测试群",
 *         "chatroom_admin_id": "wxid_70jt05y6clpq22",
 *         "chatroom_head_url": "https://wx.qlogo.cn/mmcrhead/IbQhd2Y9oKeKgAJicX73Q8icAkRCCnZPuZ3XSLiaE9lw5N93DhQoPmzPWyaibJ759icVleRFNYznv6KM/0",
 *         "chatroom_serial_no": "DE74ABB2CA5BF1BC921F838DCB1B0E47",
 *         "chatroom_remark_name": "",
 *         "chatroom_member_count": 52,
 *         "chatroom_verification": 0,
 *         "chatroom_admin_serial_no": "55984829BEFE48B35DD35E560BD33C44"
 *     },
 *     "nType": 4534,
 *     "nResult": 1,
 *     "vcResult": "SUCCESS",
 *     "nTimeStamp": 1737948359512,
 *     "vcSerialNo": "20250127112402215116416523112",
 *     "vcRobotWxId": "wxid_mi88feubut7822",
 *     "vcMerchantNo": "202407150008480",
 *     "vcRobotSerialNo": "B9242BBFE29699C36B54435F5F407F2F"
 * }
 * </pre>
 */
@Slf4j
@Component
public class _4534Handler implements CallbackHandler {

    @Resource
    private WFGIdGenerator idGenerator;

    @Resource
    private RoomMapper roomMapper;

    @Resource
    private RobotRoomMapper robotRoomMapper;

    @Override
    public String name() {
        return "获取群信息接口（异步）回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 4534;
    }

    @Override
    public void handle(Callback callback) {
        LocalDateTime now = LocalDateTime.now();
        String robotId = callback.getRobotId();
        String robotSerialNo = callback.getRobotSerialNo();
        JSONObject data = (JSONObject) callback.getData();
        String roomId = data.getString("chatroom_id");
        if (!StringUtils.hasText(roomId)) {
            log.error("获取群信息为空[id:{}, serialNo:{}, robotId:{}, robotSerialNo:{}]",
                    callback.getId(), callback.getSerialNo(), callback.getRobotId(), callback.getRobotSerialNo());
            return;
        }
        Room room = new Room()
                .setId(roomId)
                .setSerialNo(data.getString("chatroom_serial_no"))
                .setName(data.getString("chatroom_name"))
                .setOwnerId(data.getString("chatroom_admin_id"))
                .setOwnerSerialNo(data.getString("chatroom_admin_serial_no"))
                .setAvatar(data.getString("chatroom_head_url"))
                .setMemberCount(data.getInteger("chatroom_member_count"))
                .setVerification(data.getBoolean("chatroom_verification"));
        boolean roomExists = isRoomExists(data);
        if (roomExists) {
            roomMapper.updateById(room);
        } else {
            roomMapper.insert(room);
        }

        RobotRoom robotRoom = new RobotRoom()
                .setRobotId(robotId)
                .setRobotSerialNo(robotSerialNo)
                .setRoomId(roomId)
                .setRoomSerialNo(room.getSerialNo())
                .setRoomName(room.getName())
                .setTop(data.getBoolean("is_top"))
                .setRemarkName(data.getString("chatroom_remark_name"))
                .setUpdatedTime(now);

        LambdaQueryWrapper<RobotRoom> wrapper = new LambdaQueryWrapper<RobotRoom>()
                .select(RobotRoom::getId)
                .eq(RobotRoom::getRobotId, robotId)
                .eq(RobotRoom::getRoomId, roomId);
        RobotRoom oldRobotRoom = robotRoomMapper.selectOne(wrapper);
        if (oldRobotRoom != null) {
            robotRoom.setId(oldRobotRoom.getId());
            robotRoomMapper.updateById(robotRoom);
        } else {
            robotRoom.setId(idGenerator.next())
                    .setCreatedTime(now);
            robotRoomMapper.insert(robotRoom);
        }
    }

    private boolean isRoomExists(JSONObject data) {
        LambdaQueryWrapper<Room> wrapper = new LambdaQueryWrapper<Room>()
                .eq(Room::getId, data.getString("chatroom_id"));
        return roomMapper.exists(wrapper);
    }
}
